package org.shiro.demo.controller;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;
import open189.sign.SmsSender;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.joda.time.DateTime;
import org.joda.time.Minutes;
import org.joda.time.Seconds;
import org.shiro.demo.entity.AdminSms;
import org.shiro.demo.entity.Administrator;
import org.shiro.demo.entity.BindSms;
import org.shiro.demo.entity.ResponseResult;
import org.shiro.demo.entity.User;
import org.shiro.demo.entity.WeixinAccount;
import org.shiro.demo.service.IAdminService;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.utils.AESUtil;
import com.utils.CommonUtil;

@Controller
public class LoginController {
	
	@Resource(name = "smsSender")
	SmsSender smsSender;
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public @ResponseBody Object login(User user, HttpSession session, HttpServletRequest request, HttpServletResponse reponse) {

		// 获取当前的Subject
		Subject curUser = SecurityUtils.getSubject();
		// 改进，此处必须将password 解密。 AES算法的解密比加密要快100倍。TODO ING
		String DeString = null;
		try {
			DeString = AESUtil.Decrypt(user.getPassword());
			System.out.println(user.getPassword() + "解密+" + DeString);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		UsernamePasswordToken token = new UsernamePasswordToken("user;" + user.getPhone(), DeString);
		token.setRememberMe(true);
		try {
			// 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
			// 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
			// 所以这一步在调用login(token)方法时,它会走到ShiroDbRealm.doGetAuthenticationInfo()方法中
			System.out.println("1");
			curUser.login(token);
			System.out.println("2");
			// 添加信息
			/*
			 * if (null != curUser) { Session shiro_session =
			 * curUser.getSession(); if (null != shiro_session) {
			 * shiro_session.setAttribute(Keys.CURRENT_USER, user); } }
			 */
			System.out.println("3");
			System.out.println(request.getSession().getId());
			reponse.addHeader("id", request.getSession().getId());
			reponse.addHeader("Cookie", request.getHeader("Cookie"));
			User userIdDB = userService.getByPhone(user.getPhone());
			ResponseResult rr = new ResponseResult(1, request.getSession().getId(), userIdDB);
			return rr;
		} catch (AuthenticationException e) {
			// 通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
			token.clear();
			ResponseResult rr = new ResponseResult(0, "登陆失败", null);

			return rr;// 登录失败，返回空
		}
	}

	/**
	 * 明文登陆.. 后面要改进 作废
	 * 
	 * @param user
	 * @param session
	 * @param request
	 * @param reponse
	 * @return
	 */
	// @RequestMapping(value = "/login2", method = RequestMethod.POST)
	// public @ResponseBody Object login2(User user, HttpSession session,
	// HttpServletRequest request, HttpServletResponse reponse) {
	//
	// // 获取当前的Subject
	// Subject curUser = SecurityUtils.getSubject();
	//
	// UsernamePasswordToken token = new UsernamePasswordToken("user;" +
	// user.getPhone(), user.getPassword());
	// token.setRememberMe(true);
	// try {
	// //
	// 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
	// // 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
	// // 所以这一步在调用login(token)方法时,它会走到ShiroDbRealm.doGetAuthenticationInfo()方法中
	// System.out.println("1");
	// curUser.login(token);
	// System.out.println("2");
	// // 添加信息
	// /*
	// * if (null != curUser) { Session shiro_session =
	// * curUser.getSession(); if (null != shiro_session) {
	// * shiro_session.setAttribute(Keys.CURRENT_USER, user); } }
	// */
	// System.out.println("3");
	// System.out.println(request.getSession().getId());
	// reponse.addHeader("id", request.getSession().getId());
	// reponse.addHeader("Cookie", request.getHeader("Cookie"));
	// User userIdDB = userService.getByPhone(user.getPhone());
	// ResponseResult rr = new ResponseResult(1, request.getSession().getId(),
	// userIdDB);
	// return rr;
	// } catch (AuthenticationException e) {
	// // 通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
	// token.clear();
	// ResponseResult rr = new ResponseResult(0, "登陆失败", null);
	//
	// return rr;// 登录失败，返回空
	// }
	// }

	@Resource(name = "userService")
	private IUserService userService;
	@Resource(name = "adminService")
	private IAdminService adminService;

	@Resource(name = "baseService")
	private IBaseService baseService;

	/**
	 * 
	 * @param request
	 * @param reponse
	 * @param phone
	 *            手机号
	 * @param pw
	 *            密码
	 * @return ResponseResult
	 * 
	 *         用户请求发送验证码
	 * 
	 *         1）输入不能为空
	 * 
	 *         2）手机长度必须是11
	 * 
	 *         3）手机用户不为空并且已激活，不能注册
	 * 
	 *         4）手机用户为空，为新用户，发送验证码
	 * 
	 *         5）手机用户不为空，但是未激活，继续发送验证码
	 */
//	@RequestMapping(value = "/send")
//	@ResponseBody
//	public ResponseResult send(HttpServletRequest request, HttpServletResponse reponse, @RequestParam(value = "phone", required = true) String phone, @RequestParam(value = "pw", required = true) String pw) {
//		ResponseResult rr = new ResponseResult();
//		if (phone == null || pw == null) {
//			rr.setCode(0);
//			rr.setInfo("can not be null");
//			return rr;
//		}
//		System.out.println("手机号码注册" + phone);
//		if (phone.length() != 11) {
//			rr.setCode(0);
//			rr.setInfo("error phone");
//			return rr;
//		}
//		User user = userService.getByPhone(phone);
//		if (null != user && user.isActive()) {
//			rr.setCode(0);
//			rr.setInfo("phone has been actived");
//			return rr;
//		}
//		// 发短信。存储用户
//		if (user == null) {// 新用户
//			User newUser = new User();
//			newUser.setActive(false);
//			newUser.setPhone(phone);
//			int random = (int) (Math.random() * 10000) + 1000;// 取值范围是[1000,10000)。
//			newUser.setSmsCode(String.valueOf(random));// 存储 随机数
//			newUser.setPassword(pw);
//			newUser.setName("phone_" + phone);
//			userService.save(newUser);
//			// 发送 手机短信。
//			try {
//				postSMS(random, phone);
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			rr.setCode(1);
//			rr.setInfo("发送验证码成功");
//			return rr;
//		} else {
//			if (!user.isActive()) { // 重新发送验证码
//
//				user.setActive(false);
//				user.setPhone(phone);
//				int random = (int) (Math.random() * 10000) + 1000;// 取值范围是[1000,10000)。
//				user.setSmsCode(String.valueOf(random));// 存储 随机数
//				user.setPassword(pw);
//				userService.update(user);
//				// 发送 手机短信。
//				// 发送 手机短信。
//				try {
//					postSMS(random, phone);
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//				rr.setCode(1);
//				rr.setInfo("重新发送验证码成功");
//				return rr;
//			}
//		}
//		return rr;
//	}

	/**
	 * 
	 * @param request
	 * @param reponse
	 * @param phone
	 * @param code
	 * @return
	 * 
	 *         用户核对验证码
	 * 
	 *         1）手机号，验证码不能为空
	 * 
	 *         2）手机长度必须等于11
	 * 
	 *         3.1）用户不为空，且处于未激活状态。验证码是否正确，正确，则可以成功验证。
	 * 
	 *         3.2）其他情况，全视为操作失败
	 */
	// @RequestMapping(value = "/validate")
	// @ResponseBody
	// public ResponseResult validate(HttpServletRequest request,
	// HttpServletResponse reponse, @RequestParam(value = "phone", required =
	// true) String phone, @RequestParam(value = "code", required = true) String
	// code) {
	// ResponseResult rr = new ResponseResult();
	// rr.setCode(0);
	// System.out.println("手机号码注册" + phone);
	// if (phone == null || code == null) {
	// rr.setInfo("can not be null");
	// return rr;
	// }
	// if (phone.length() != 11) {
	// rr.setInfo("error phone");
	// return rr;
	// }
	// User user = userService.getByPhone(phone);
	// if (user != null && !user.isActive()) {
	// if (code.equals(user.getSmsCode())) {
	// user.setActive(true);
	// userService.update(user);
	// rr.setCode(1);
	// rr.setInfo("成功验证");
	// return rr;
	// } else {
	// rr.setInfo("error code 错误验证码");
	// return rr;
	// }
	// } else {
	// rr.setInfo("用户不存在或者已经激活");
	// return rr;
	// }
	//
	// }

	/**
	 * {"res_code":"0","res_message":"Success","access_token":
	 * "b286febd2a8174a6ababcfe65800f07d1406709153083","expires_in":2592000}
	 * 有效期是30天，验证时间是2014年7月30号
	 * 
	 * @param random
	 * @return
	 * @throws Exception
	 */
	private boolean postSMS(int random, String phone) throws Exception {
		try {
			// 发送手机 短消息
			URL postUrl = new URL("http://api.189.cn/v2/emp/templateSms/sendSms");
			// 打开连接
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
			// acceptor_tel=13123185312&template_id=91000001&template_param={"日报":"nihao","晚报":"nidao","url":"www.baidu.com"}&app_id=418839000000031xxx&access_token=c49fabf158e25985ed1284a75716a9b9137067210xxxx&timestamp=2013-09-06+16%3A07%3A42
			// http正文内，因此需要设为true
			connection.setDoOutput(true);
			// Read from the connection. Default is true.
			connection.setDoInput(true);
			// Set the post method. Default is GET
			connection.setRequestMethod("POST");
			// Post cannot use caches
			// Post 请求不能使用缓存
			connection.setUseCaches(false);
			// connection.setRequestProperty("Content-Type",
			// "application/json");
			// 要注意的是connection.getOutputStream会隐含的进行connect。
			connection.connect();
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			// The URL-encoded contend
			// 正文，正文内容其实跟get的URL中'?'后的参数字符串一致
			// 2014-08-04+15%3A45%3A40
			DateTime dt = new DateTime();
			String time = dt.plusMinutes(2).toString("yyyy-MM-dd HH:mm:ss");
			// phone="15201967267";
			String content = "acceptor_tel=" + phone + "&template_id=91001874&template_param={\"param1\":\"Mr.Miss\",\"param2\":\"" + random + "\",\"param3\":\"30分钟\"}&app_id=201286860000036675&access_token=b286febd2a8174a6ababcfe65800f07d1406709153083&timestamp=" + time;

			// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
			out.write(content.getBytes("utf-8"));

			out.flush();
			out.close(); // flush and close
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			System.out.println("=============================");
			System.out.println("Contents of post request");
			System.out.println("=============================");
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
			System.out.println("=============================");
			System.out.println("Contents of post request ends");
			System.out.println("=============================");
			reader.close();
			connection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
		// 成功{"res_code":"0","res_message":"Success","idertifier":"90610730164302806669"}
		// 成功{"res_code":"0","res_message":"Success","idertifier":"90610730165225806924"}
	}

	// private DoubanInfo getDouban(String token) {
	// DoubanInfo doubanInfo = null;
	// try {
	//
	// String resp = DoubanUsersAPI.getLoggedInUserProfileNot(token);
	// ObjectMapper om = new ObjectMapper();
	// doubanInfo = om.readValue(resp, DoubanInfo.class);
	// } catch (Exception e) {
	// e.printStackTrace();
	// return null;
	// }
	// if (doubanInfo.getUid() != null) {
	// // Weibo id 不存在。
	// return doubanInfo;
	// } else {
	// return doubanInfo;
	// }
	// }

	/**
	 * 管理员登陆，登陆之后成为admin
	 * 
	 * @param admin
	 * @param session
	 * @param request
	 * @param reponse
	 * @return
	 */
	@RequestMapping(value = "/adminlogin", method = RequestMethod.POST)
	public @ResponseBody Object adminLogin(Administrator admin, HttpSession session, HttpServletRequest request, HttpServletResponse reponse) {
		ResponseResult rr = new ResponseResult(0, "", null);
		// 判断验证码
		// String code = (String) session.getAttribute("validateCode");
		// String submitCode = WebUtils.getCleanParam(request, "validateCode");

		/*
		 * if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(code,
		 * submitCode.toLowerCase())) { return "redirect:/"; }
		 */

		// 获取当前的Subject
		Subject curUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken("admin;" + admin.getPhone(), admin.getPassword());
		token.setRememberMe(true);
		try {
			// 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
			// 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
			// 所以这一步在调用login(token)方法时,它会走到ShiroDbRealm.doGetAuthenticationInfo()方法中
			System.out.println("1");
			curUser.login(token);
			System.out.println("2");
			// 添加信息
			/*
			 * if (null != curUser) { Session shiro_session =
			 * curUser.getSession(); if (null != shiro_session) {
			 * shiro_session.setAttribute(Keys.CURRENT_USER, user); } }
			 */
			System.out.println("3");
			System.out.println(request.getSession().getId());
			reponse.addHeader("id", request.getSession().getId());
			reponse.addHeader("Cookie", request.getHeader("Cookie"));
			rr.setCode(1);
			rr.setInfo("redirect:html/admin-index.html");
			rr.setObject("redirect:html/admin-index.html");
			return rr;
			// return request.getSession().getId();
		} catch (AuthenticationException e) {
			// 通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
			token.clear();
			rr.setCode(0);
			rr.setInfo("登录失败");
			return rr;// 登录失败，返回空
		}
	}

	/**
	 * 向管理员的手机发送密码
	 * 
	 * 一天一次
	 * 
	 * @param admin
	 * @param session
	 * @param request
	 * @param reponse
	 * @return
	 */
	@RequestMapping(value = "/sendpassword", method = RequestMethod.POST)
	public @ResponseBody Object sendpassword(String phone, HttpSession session, HttpServletRequest request, HttpServletResponse reponse) {
		ResponseResult rr = new ResponseResult(0, "", null);

		Administrator admin = adminService.getByPhone(phone);
		if (admin == null) {
			rr.setCode(0);
			rr.setInfo("管理员不存在");
			return rr;
		}
		try {
			// 存在管理员，查看上一次发送密码的时间。
			AdminSms adminSms = baseService.getById(AdminSms.class, phone);
			if (adminSms != null) {
				org.joda.time.DateTime createTime = new DateTime(adminSms.getCreateTime());
				String timeInDb = createTime.toString("yyyy-MM-dd");
				DateTime timeInNow = new DateTime(new Date());
				if (timeInNow.toString("yyyy-MM-dd").equals(timeInDb)) {
					rr.setCode(0);
					rr.setInfo("密码只能一天发送一次");
					return rr;
				} else {// 发送密码。AdminSms更新到数据库
					if (smsSender.postSMS1(admin.getPassword(), phone)) {
						adminSms.setCreateTime(new Date());
						baseService.update(adminSms);
						rr.setCode(1);
						rr.setInfo("成功 发送密码");
						return rr;
					} else {
						adminSms.setCreateTime(new Date());
						adminSms.setCode("fail");
						baseService.update(adminSms);
						rr.setCode(0);
						rr.setInfo("发送短信的时候失败了，请联系管理员");
						return rr;
					}
				}
			} else {
				// 发送密码。全新的AdminSms插入数据库
				if (smsSender.postSMS1(admin.getPassword(), phone)) {
					AdminSms sms = new AdminSms();
					sms.setPhone(phone);
					sms.setCreateTime(new Date());
					baseService.save(sms);

					rr.setCode(1);
					rr.setInfo("成功 发送密码");
					return rr;
				} else {
					AdminSms sms = new AdminSms();
					sms.setCode("fail");// 0 失败了
					sms.setPhone(phone);
					sms.setCreateTime(new Date());
					baseService.save(sms);

					rr.setCode(0);
					rr.setInfo("发送短信的时候失败了，请联系管理员");
					return rr;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("系统内部出错");
			return rr;
		}

	}

	/**
	 * 为了 绑定 管理员的微信号码
	 * 
	 * 而发送验证码
	 * 
	 * 
	 * @param admin
	 * @param session
	 * @param request
	 * @param reponse
	 * @return
	 */
	@RequestMapping(value = "/sendBindCode", method = RequestMethod.GET)
	public @ResponseBody Object sendBindCode(String phone, HttpSession session, HttpServletRequest request, HttpServletResponse reponse) {
		ResponseResult rr = new ResponseResult(0, "", null);

		Administrator admin = adminService.getByPhone(phone);
		if (admin == null) {
			rr.setInfo("管理员不存在");
			return rr;
		}
		WeixinAccount weixinAccount = baseService.getById(WeixinAccount.class, phone);
		if (weixinAccount != null) {
			rr.setInfo("微信号已绑定");
			return rr;
		}
		try {
			// 取值范围是[1000,10000)、、随机验证码
			int random = (int) (Math.random() * 10000) + 1000;

			// 存在管理员，查看上一次发送密码的时间。
			BindSms bindSms = baseService.getById(BindSms.class, phone);
			if (bindSms != null) {

				if (isRepeate(bindSms.getCreateTime())) {// 重复了
					// 30s未到。
					return new ResponseResult(0, "请等待30s之后再请求", null);
				} else {// 发送 验证码。bindSms更新到数据库
					if (smsSender.postSMS(random + "", phone)) {
						bindSms.setCreateTime(new Date());
						bindSms.setCode(String.valueOf(random));
						bindSms.setType("wechat");
						baseService.update(bindSms);
						rr.setCode(1);
						rr.setInfo("成功 发送验证码");
						return rr;
					} else {
						bindSms.setCreateTime(new Date());
						bindSms.setType("wechat");
						bindSms.setCode("fail");
						baseService.update(bindSms);
						rr.setCode(0);
						rr.setInfo("发送短信的时候失败了，请联系管理员");
						return rr;
					}
				}
			} else {
				// 发送 验证码。bindSms更新到数据库
				if (smsSender.postSMS(random + "", phone)) {
					bindSms = new BindSms();
					bindSms.setPhone(phone);
					bindSms.setCreateTime(new Date());
					bindSms.setCode(String.valueOf(random));
					bindSms.setType("wechat");
					baseService.save(bindSms);

					rr.setCode(1);
					rr.setInfo("成功 发送 验证码");
					return rr;
				} else {
					bindSms = new BindSms();
					bindSms.setCode("fail");// 0 失败了
					bindSms.setPhone(phone);
					bindSms.setType("wechat");
					bindSms.setCreateTime(new Date());
					baseService.save(bindSms);

					rr.setCode(0);
					rr.setInfo("发送短信的时候失败了，请联系管理员");
					return rr;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("系统内部出错");
			return rr;
		}

	}

	/**
	 * 验证 绑定 管理员的微信号码
	 * 
	 * 
	 * @param session
	 * @param request
	 * @param reponse
	 * @return
	 */
	@RequestMapping(value = "/verifyBindCode", method = RequestMethod.GET)
	public @ResponseBody Object verifyBindCode(String phone, String mcode, String code, HttpSession session, HttpServletRequest request, HttpServletResponse reponse) {
		ResponseResult rr = new ResponseResult(0, "", null);
		if (StringUtils.isEmpty(mcode) || StringUtils.isEmpty(phone)) {
			rr.setInfo("手机号或者与验证码不能为空");
			return rr;
		}
		Administrator admin = adminService.getByPhone(phone);
		if (admin == null) {
			rr.setInfo("管理员不存在");
			return rr;
		}
		WeixinAccount weixinAccount = baseService.getById(WeixinAccount.class, phone);
		if (weixinAccount != null) {
			rr.setInfo("微信号已绑定");
			return rr;
		}

		try {

			// 存在管理员，查看 验证码是否失效了
			BindSms bindSms = baseService.getById(BindSms.class, phone);
			if (bindSms != null) {

				if (isExpired(bindSms.getCreateTime())) {// 重复了
					// 30s未到。
					return new ResponseResult(0, "验证码已失效", null);
				} else {// 对比验证码
					if (bindSms.getCode().equals(mcode)) {// 正确。 存入openid
						WeixinAccount account = new WeixinAccount();
						account.setCreateTime(new Date());
						account.setPhone(phone);

						// 访问 微信平台得到openid
						// 商户相关资料
						String appid = "wx1d8e9a967a8c62bd";
						String appsecret = "c687ad8537af8d8e1ca2fc573095a426";
						String partner = "1227994702";
						String partnerkey = "BdplgSwZUTqFBXdCikJB91kx6aCiIF3O";

						String openId = "";
						String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret + "&code=" + code + "&grant_type=authorization_code";

						JSONObject jsonObject = CommonUtil.httpsRequest(URL, "GET", null);
						if (null != jsonObject) {
							openId = jsonObject.getString("openid");
						}

						account.setOpenid(openId);// code 转 openid
						baseService.save(account);

						baseService.delete(BindSms.class, bindSms.getPhone());//
						return new ResponseResult(1, "成功绑定", null);
					} else {
						return new ResponseResult(0, "验证码无效", null);
					}
				}
			} else {
				return new ResponseResult(0, "验证码无效", null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("系统内部出错");
			return rr;
		}

	}

	// @RequestMapping(value = "/adminlogin2")
	// public @ResponseBody
	// String adminLogin2(Administrator admin, HttpSession session,
	// HttpServletRequest request, HttpServletResponse reponse) {
	// // 判断验证码
	// String code = (String) session.getAttribute("validateCode");
	// String submitCode = WebUtils.getCleanParam(request, "validateCode");
	//
	// /*
	// * if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(code,
	// * submitCode.toLowerCase())) { return "redirect:/"; }
	// */
	//
	// // 获取当前的Subject
	// Subject curUser = SecurityUtils.getSubject();
	// UsernamePasswordToken token = new
	// UsernamePasswordToken("admin;"+admin.getName(), admin.getPassword());
	// token.setRememberMe(true);
	// try {
	// //
	// 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
	// // 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
	// // 所以这一步在调用login(token)方法时,它会走到ShiroDbRealm.doGetAuthenticationInfo()方法中
	// System.out.println("1");
	// curUser.login(token);
	// System.out.println("2");
	// // 添加信息
	// /*
	// * if (null != curUser) { Session shiro_session =
	// * curUser.getSession(); if (null != shiro_session) {
	// * shiro_session.setAttribute(Keys.CURRENT_USER, user); } }
	// */
	// System.out.println("3");
	// System.out.println(request.getSession().getId());
	// reponse.addHeader("id", request.getSession().getId());
	// reponse.addHeader("Cookie", request.getHeader("Cookie"));
	// return request.getSession().getId();
	// } catch (AuthenticationException e) {
	// // 通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
	// token.clear();
	// return "";// 登录失败，返回空
	// }
	// }

	private int expried = 10; // 过期时间 （10分钟）

	private boolean isExpired(Date date) {
		DateTime from = new DateTime(date);
		DateTime to = new DateTime(new Date());
		if (Minutes.minutesBetween(from, to).getMinutes() > expried) {
			return true;// 过期了
		}
		return false;
	}

	private int repeateTime = 30; // 30秒 发一次

	private boolean isRepeate(Date date) {
		DateTime from = new DateTime(date);
		DateTime to = new DateTime(new Date());
		// 间隔 小于 30秒
		if (Seconds.secondsBetween(from, to).getSeconds() < repeateTime) {
			return true;// 重复了
		}
		return false;
	}
}
